import { JavascriptGenerator, javascriptGenerator } from "blockly/javascript";
import { Tanslate } from "./translate";
import * as Blockly from 'blockly/core';
import { getValue } from "./com";
export namespace Browser {
    const blocks = [
        {
            "key": "await_time",
            "message0": "%{await_time} %1 %{milliseconds}",
            "args0": [
                {
                    "type": "field_number",
                    "name": "time",
                    "value": 1000,
                    "min": 0,
                    "max": 60 * 1000,
                    "precision": 1
                }
            ],
            "nextStatement": null,
            "previousStatement": null,
            "colour": 200
        },
        {
            "key": "set_cache",
            "message0": "%{set_cache} \n %{key} %1 %{value} %2",
            "args0": [
                {
                    "type": "input_value",
                    "name": "key",
                    "check": "String"
                },
                {
                    "type": "input_value",
                    "name": "value"
                }
            ],
            "nextStatement": null,
            "previousStatement": null,
            "colour": 200
        },
        {
            "key": "get_cache",
            "message0": "%{get_cache} %{key} %1",
            "args0": [
                {
                    "type": "input_value",
                    "name": "key",
                    "check": "String"
                }
            ],
            "output": null,
            "colour": 200
        },
        {
            "key": "clear_cache",
            "message0": "%{clear_cache} %{key} %1",
            "args0": [
                {
                    "type": "input_value",
                    "name": "key",
                    "check": "String"
                }
            ],
            "nextStatement": null,
            "previousStatement": null,
            "colour": 200
        },
        {
            "key": "open_tab",
            "message0": "%{open_tab} %{net_url} %1 %{element_name} %2",
            "args0": [
                {
                    "type": "input_value",
                    "name": "url",
                    "check": "String"
                },
                {
                    "type": "field_input",
                    "name": "name",
                    "text": "_blank"
                }
            ],
            "output": "open_tab",
            "nextStatement": null,
            "previousStatement": null,
            "inputsInline": true,
            "colour": 200
        },
        {
            "key": "close_tab",
            "message0": "%{close_tab} %1",
            "args0": [
                {
                    "type": "input_value",
                    "name": "tab",
                    "check": "open_tab"
                }
            ],
            "nextStatement": null,
            "previousStatement": null,
            "colour": 200
        },
        {
            "key": "read_clipboard",
            "message0": "%{read_clipboard}",
            "output": "Promise",
            "colour": 200
        },
        {
            "key": "write_clipboard",
            "message0": "%{write_clipboard} %1",
            "args0": [
                {
                    "type": "input_value",
                    "name": "value",
                    "check": "String"
                }
            ],
            "nextStatement": null,
            "previousStatement": null,
            "output": "Promise",
            "colour": 200
        },
        {
            "key": "console",
            "message0": "%{console} %{print} %1 %2",
            "args0": [
                {
                    "type": "field_dropdown",
                    "name": "type",
                    "options": [
                        ["%{console_log}", "log"],
                        ["%{console_error}", "error"],
                        ["%{console_info}", "info"],
                        ["%{console_warn}", "warn"]
                    ]
                },
                {
                    "type": "input_value",
                    "name": "value"
                }
            ],
            "nextStatement": null,
            "previousStatement": null,
            "colour": 200
        },
        {
            "key": "alert",
            "message0": "%{alert} %1",
            "args0": [
                {
                    "type": "input_value",
                    "name": "value"
                }
            ],
            "nextStatement": null,
            "previousStatement": null,
            "colour": 200
        },
        {
            "key": "prompt",
            "message0": "%{prompt} %1",
            "args0": [
                {
                    "type": "input_value",
                    "name": "value"
                }
            ],
            "output": "String",
            "colour": 200
        },
        {
            'key': 'set_timeout',
            'message0': '%{set_timeout_wait} %1 %{set_timeout_ms}',
            'args0': [
                {
                    'type': 'input_value',
                    'name': 'TIME',
                    'check': 'Number',
                },
            ],
            'message1': '%{do} %1',
            'args1': [
                {
                    'type': 'input_statement',
                    'name': 'DO0',
                },
            ],
            'previousStatement': null,
            'nextStatement': null,
            "output": "Timeout",
            'colour': 200
        },
        {
            "key": "clear_timeout",
            "message0": "%{clear_timeout} %1",
            "args0": [
                {
                    "type": "input_value",
                    "name": "VALUE",
                    "check": "Timeout"
                }
            ],
            'previousStatement': null,
            'nextStatement': null,
            "inputsInline": true,
            "colour": 200
        },
        {
            'key': 'set_interval',
            'message0': '%{set_interval_wait} %1 %{set_timeout_ms}',
            'args0': [
                {
                    'type': 'input_value',
                    'name': 'TIME',
                    'check': 'Number',
                },
            ],
            'message1': '%{set_interval_repeat}%{do} %1',
            'args1': [
                {
                    'type': 'input_statement',
                    'name': 'DO0',
                },
            ],
            'previousStatement': null,
            'nextStatement': null,
            "output": "Interval",
            'colour': 200
        },
        {
            "key": "clear_interval",
            "message0": "%{clear_interval} %1",
            "args0": [
                {
                    "type": "input_value",
                    "name": "VALUE",
                    "check": "Interval"
                }
            ],
            'previousStatement': null,
            'nextStatement': null,
            "inputsInline": true,
            "colour": 200
        },
        {
            "key": "location_get",
            "message0": "%{location_get} %1",
            "args0": [
                {
                    'type': 'field_dropdown',
                    'name': 'GET',
                    'options': [
                        ['%{location_get_hash}', 'hash'],
                        ['%{location_get_search}', 'search'],
                        ['%{location_get_host}', 'host'],
                        ['%{location_get_hostname}', 'hostname'],
                        ['%{location_get_port}', 'port'],
                        ['%{location_get_pathname}', 'pathname'],
                        ['%{location_get_protocol}', 'protocol'],
                        ['%{location_get_origin}', 'origin'],
                        ['%{location_get_href}', 'href'],
                        ['%{location_reload}', 'reload'],
                    ],
                },
            ],
            "output": ["String", "Number", "Function"],
            'previousStatement': null,
            'nextStatement': null,
            "inputsInline": true,
            "colour": 200
        },
        {
            "key": "search_params_get",
            "message0": "%{from} %1 %{search_params_get} %2",
            "args0": [
                {
                    "type": "input_value",
                    "name": "URL",
                    "check": "String"
                },
                {
                    "type": "input_value",
                    "name": "KEY",
                    "check": "String"
                }
            ],
            "output": "String",
            "inputsInline": true,
            "colour": 200
        },
        {
            "key": "navigator_get",
            "message0": "%{navigator_get} %1",
            "args0": [
                {
                    'type': 'field_dropdown',
                    'name': 'GET',
                    'options': [
                        ['%{location_get_appName}', 'appName'],
                        ['%{location_get_appCodeName}', 'appCodeName'],
                        ['%{location_get_appVersion}', 'appVersion'],
                        ['%{location_get_platform}', 'platform'],
                        ['%{location_get_userAgent}', 'userAgent'],
                        ['%{location_get_language}', 'language'],
                        ['%{location_get_languages}', 'languages'],
                    ],
                },
            ],
            "output": ["String", "Number", "Array"],
            'previousStatement': null,
            'nextStatement': null,
            "inputsInline": true,
            "colour": 200
        },
        {
            "key": "inner_width",
            "message0": "%{inner_width}",
            "output": "Number",
            "colour": 200
        },
        {
            "key": "inner_height",
            "message0": "%{inner_height}",
            "output": "Number",
            "colour": 200
        },
    ]
    export function init() {
        initGenerator()
        Tanslate.tr(blocks).forEach((item: any) => {
            Blockly.Blocks[item.key] = {
                init: function (this: any) {
                    this.jsonInit(item);
                }
            }
        })
    }

    export function getTools() {
        const netBlocks = {
            kind: 'category',
            name: Blockly.Msg['browser'],
            "colour": 200,
            contents: [] as any[]
        }
        blocks.forEach((item: any) => {
            netBlocks.contents.push({
                kind: 'block',
                type: item.key
            })
        })

        return netBlocks
    }

    function initGenerator() {

        javascriptGenerator.forBlock['await_time'] = function (block: Blockly.Block, _generator: JavascriptGenerator) {
            const time = block.getFieldValue('time');
            return `await new Promise(resolve => setTimeout(resolve, ${time}));\n`;
        }

        javascriptGenerator.forBlock['set_cache'] = function (block: Blockly.Block, generator: JavascriptGenerator) {
            const key = getValue(block, generator, 'key');
            const value = getValue(block, generator, 'value');
            if (!key || value === undefined) {
                throw new Error(block.id);
            }
            return `localStorage.setItem(${key}, ${value});\n`;
        }
        javascriptGenerator.forBlock['get_cache'] = function (block: Blockly.Block, generator: JavascriptGenerator) {
            const key = getValue(block, generator, 'key');
            if (!key) {
                throw new Error(block.id);
            }
            return `localStorage.getItem(${key})`;
        }
        javascriptGenerator.forBlock['clear_cache'] = function (block: Blockly.Block, generator: JavascriptGenerator) {
            const key = getValue(block, generator, 'key');
            if (!key) {
                throw new Error(block.id);
            }
            return `localStorage.removeItem(${key});\n`;
        }

        javascriptGenerator.forBlock['open_tab'] = function (block: Blockly.Block, generator: JavascriptGenerator) {
            const value = getValue(block, generator, 'url');
            const name = block.getFieldValue('name');
            if (!value) {
                throw new Error(block.id);
            }
            if(block.outputConnection?.targetBlock()) {
                return `window.open(${value}, '${name}')`;
            }
            return `window.open(${value}, '${name}');\n`;
        }
        javascriptGenerator.forBlock['close_tab'] = function (block: Blockly.Block, generator: JavascriptGenerator) {
            const tab = getValue(block, generator, 'tab')?.trim();
            if (!tab) {
                throw new Error(block.id);
            }
            return `${tab}.close();\n`;
        }
        javascriptGenerator.forBlock['read_clipboard'] = function () {
            return `navigator.clipboard.readText()`;
        }

        javascriptGenerator.forBlock['write_clipboard'] = function (block: Blockly.Block, generator: JavascriptGenerator) {
            const value = getValue(block, generator, 'value')?.trim();
            if (!value) {
                throw new Error(block.id);
            }
            return `navigator.clipboard.writeText(${value});\n`;
        }

        javascriptGenerator.forBlock['console'] = function (block: Blockly.Block, generator: JavascriptGenerator) {
            const ct = block.getFieldValue('type');
            const value = getValue(block, generator, 'value');
            if (!value) {
                throw new Error(block.id);
            }
            return `console.${ct}(${value});\n`;
        }

        javascriptGenerator.forBlock['alert'] = function (block: Blockly.Block, generator: JavascriptGenerator) {
            const value = getValue(block, generator, 'value');
            if (!value) {
                throw new Error(block.id);
            }
            return `window.alert(${value});\n`;
        }

        javascriptGenerator.forBlock['prompt'] = function (block: Blockly.Block, generator: JavascriptGenerator) {
            const value = getValue(block, generator, 'value');
            if (!value) {
                throw new Error(block.id);
            }
            return `window.prompt(${value})`;
        }

        javascriptGenerator.forBlock['set_timeout'] = function (block: Blockly.Block, generator: JavascriptGenerator) {
            const body = block.getInputTargetBlock('DO0');
            const TIME = getValue(block, generator, 'TIME')
            let lines = ''
            if (body) {
                const line = generator.blockToCode(body)
                lines = (typeof line === 'string' ? line : line.join('\n'))
            }
            if (!TIME) {
                throw new Error(block.id);
            }
            if(block.outputConnection?.targetBlock()) {
                return `setTimeout(() => {\n${lines}\n}, ${TIME})`;
            }
            return `setTimeout(() => {\n${lines}\n}, ${TIME});\n`;
        }

        javascriptGenerator.forBlock['clear_timeout'] = function (block: Blockly.Block, generator: JavascriptGenerator) {
            const VALUE = getValue(block, generator, 'VALUE')
            if (!VALUE) {
                throw new Error(block.id);
            }
            return `clearTimeout(${VALUE});`;
        }

        javascriptGenerator.forBlock['set_interval'] = function (block: Blockly.Block, generator: JavascriptGenerator) {
            const body = block.getInputTargetBlock('DO0');
            const TIME = getValue(block, generator, 'TIME')
            let lines = ''
            if (body) {
                const line = generator.blockToCode(body)
                lines = (typeof line === 'string' ? line : line.join('\n'))
            }
            if (!TIME) {
                throw new Error(block.id);
            }
            if(block.outputConnection?.targetBlock()) {
                return `setInterval(() => {\n${lines}\n}, ${TIME})`;
            }
            return `setInterval(() => {\n${lines}\n}, ${TIME});`;
        }

        javascriptGenerator.forBlock['clear_interval'] = function (block: Blockly.Block, generator: JavascriptGenerator) {
            const VALUE = getValue(block, generator, 'VALUE')
            if (!VALUE) {
                throw new Error(block.id);
            }
            return `clearInterval(${VALUE});`;
        }

        javascriptGenerator.forBlock['location_get'] = function (block: Blockly.Block, generator: JavascriptGenerator) {
            const GET = getValue(block, generator, 'GET')
            if (!GET) {
                throw new Error(block.id);
            }
            return `location.${GET}`;
        }

        javascriptGenerator.forBlock['navigator_get'] = function (block: Blockly.Block, generator: JavascriptGenerator) {
            const GET = getValue(block, generator, 'GET')
            if (!GET) {
                throw new Error(block.id);
            }
            return `navigator.${GET}`;
        }

        javascriptGenerator.forBlock['search_params_get'] = function (block: Blockly.Block, generator: JavascriptGenerator) {
            const URL = getValue(block, generator, 'URL')
            const KEY = getValue(block, generator, 'KEY')
            if (!URL || !KEY) {
                throw new Error(block.id);
            }
            return `(new URL(${URL}).searchParams.get(${KEY}))`;
        }

        javascriptGenerator.forBlock['inner_width'] = function () {
            return 'window.innerWidth';
        }

        javascriptGenerator.forBlock['inner_height'] = function () {
            return 'window.innerHeight';
        }
    }
}